/*
 * @Author: c
 * @Date: 2024-01-14 10:14:24
 * @LastEditTime: 2024-01-17 22:46:29
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\common\validate\index.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// Copyright 2024 Administrator
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, registerDecorator } from 'class-validator';

export function IsNotEmptyArray(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: 'isNotEmptyArray',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return Array.isArray(value) && value.length > 0;
                }
            }
        });
    };
}

/**
 * 自定义校验
 * @param validationOptions 
 * @returns 
 */
export function IsStringArray(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: 'isStringArray',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    let arr = JSON.parse(value)
                    return arr && Array.isArray(arr) && arr.length > 0;
                }
            }
        });
    };
}


/**
 * 异步校验
 */
@ValidatorConstraint({ name: 'customAsyncValidator', async: true })
export class CustomAsyncValidator implements ValidatorConstraintInterface {
  async validate(value: any): Promise<boolean> {
    // 异步验证逻辑
    return
  }

  defaultMessage(): string {
    return 'Custom validation failed';
  }
}
